from xiaoyiwy.xiaoyi.config import *
import time

db = mysql()

def get_index_dict(cursor):
    # 获取数据库对应表中的字段名
    index_dict = dict()
    index = 0
    for desc in cursor.description:
        index_dict[desc[0]] = index
        index = index + 1
    return index_dict

def drug_box_list(openid):
    conn = db.connection()
    cursor = conn.cursor()
    sql = "select drug_id,drug_name from drug_box where open_id = '%d'" % openid
    cursor.execute(sql)
    conn.commit()
    data = cursor.fetchall()
    desc = get_index_dict(cursor)
    res = []
    for datai in data:  # 重新生成字典
        resi = {}
        for key in desc:
            resi[key] = datai[desc[key]]
        res.append(resi)
    drug_data = {
        "code": 1,
        "error": "",
        "data": res
    }
    return drug_data

def drug_box(open_id,drug_id,drug_name,delete):
    conn = db.connection()
    cursor = conn.cursor()
    if delete == '1':
        now = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
        sql = "UPDATE drug_box SET update_time= '%s',state = '1' WHERE drug_id = '%d'" % (now,drug_id)
        try:
            cursor.execute(sql)
            conn.commit()
        except:
            conn.rollback()
            return "报错了"
        data = {
            "code": 1,
            "state": drug_name+"已移除药箱!"
        }
    else:
        select_sql = "select drug_id from drug_box where drug_id = '%d' and state = '%s'" % (drug_id,delete)
        drugrepeat = cursor.execute(select_sql)
        conn.commit()
        if drugrepeat == 0:
            sql = "INSERT INTO drug_box (open_id,drug_id,drug_name,state) VALUES ('%d','%d','%s','%s')" % (
                open_id, drug_id, drug_name, delete)
            try:
                cursor.execute(sql)
                conn.commit()
            except:
                conn.rollback()
                return "报错了"
            data = {
                "code": 1,
                "state": drug_name+"已加入药箱."
            }
        else:
            data = {
                "code": 0,
                "state": drug_name+"已加入药箱,不用重复添加."
            }
    mysql_close(cursor, conn)
    return data